import advListView from '$v/advList'

import {
  isLoginRequest
} from '../api/admin'

import {
  addAdvRequest,
  advListRequest
} from '../api/adv'

//封装一个获取所有广告列表的函数
const getAllAdvList = async (res) => {
  //发送请求
  try {
    //一旦return 则当前函数返回一个promise实例 值为当前await的返回值
    return await advListRequest();
  } catch (e) {
    alert("查询出现异常" + e.message);
    //判断是否是权限异常
    if (!e.isLogin) {
      return router.go("/login");
    }
  }

}

export default async (req, res) => {
  //路由切换的时候验证登录
  try {
    await isLoginRequest()
  } catch (e) {
    //请求异常后提示用户
    alert("有异常" + e.message)

    //判断是否权限异常
    if (!e.isLogin) {
      return router.go('/login')
    }
  }

  //调用获取adv列表的函数
  const advList = await getAllAdvList()
  console.log(advList);
  //根据数据渲染
  res.render(advListView({
    advList
  }))


  //添加广告逻辑
  document.onclick = async function (e) {
    if (e.target.id === 'adv-save') {
      //收集表单数据 使用formData
      const myForm = new FormData(document.advForm);
      console.log(myForm.get('advTitle'));
      console.log(myForm.get('advType'));
      console.log(myForm.get('advOrder'));
      console.log(myForm.get('advPic'));

      if (!myForm.get("advTitle") || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")) {
        return alert("添加的内容不能有空的！！！！")
      }

      //发送请求
      try {
        await addAdvRequest(myForm)
        alert("添加广告成功")
        //关闭添加广告的弹窗
        document.getElementById("addClose").click();

        //把预览的img隐藏
        const oPreImg = document.getElementById('preImg');
        oPreImg.style.display = "none"

        //清空表单
        document.advForm.reset();

        //重新渲染
        //调用获取adv列表的函数
        const advList = await getAllAdvList()
        // console.log(advList);
        //根据数据渲染
        res.render(advListView({
          advList
        }))


      } catch (e) {
        alert("添加广告异常" + e.message);
        //判断是否是权限异常
        if (!e.isLogin) {
          //关闭添加广告的弹窗再跳转
          document.getElementById("addClose").click();
          return router.go("/login");
        }
      }

    }
  }

  document.onchange = function (e) {
    if (e.target.id === "advPic") {
      const reader = new FileReader();
      reader.readAsDataURL(e.target.files[0])
      reader.onload = function (e) {
        // console.log(e.target.result);
        //把当前的读取的base64格式 给到img
        const oPreImg = document.getElementById('preImg');
        oPreImg.src = e.target.result;
        oPreImg.style.display = "block"
      }
    }
  }
}